/**
 * 草稿箱管理页面
 * 
 * 统一管理所有类型的草稿内容（新闻、公告等）
 */
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import { useNews } from '@/hooks/useNews';
import { useAnnouncements } from '@/hooks/useAnnouncements';
import { useQueryClient } from '@tanstack/react-query';

// 内容类型枚举
type ContentType = 'all' | 'news' | 'announcements';

// 统一的草稿项目接口
interface DraftItem {
  id: number;
  title: string;
  excerpt?: string;
  category: string;
  type: 'news' | 'announcements';
  created_at: string;
  updated_at?: string;
}

export default function DraftManagement() {
  const [contentType, setContentType] = useState<ContentType>('all');
  const [searchTerm, setSearchTerm] = useState('');
  
  const queryClient = useQueryClient();

  // 获取新闻草稿
  const { data: newsData, isLoading: newsLoading } = useNews({
    keyword: searchTerm,
    published_only: false,
    page: 1,
    size: 50
  });

  // 获取公告草稿
  const { data: announcementsData, isLoading: announcementsLoading } = useAnnouncements({
    keyword: searchTerm,
    published_only: false,
    page: 1,
    size: 50
  });

  const isLoading = newsLoading || announcementsLoading;

  // 合并和筛选草稿数据
  const getDraftItems = (): DraftItem[] => {
    const items: DraftItem[] = [];

    // 添加新闻草稿
    if (newsData?.items && (contentType === 'all' || contentType === 'news')) {
      const newsDrafts = newsData.items
        .filter(item => !item.is_published)
        .map(item => ({
          id: item.id,
          title: item.title,
          excerpt: item.excerpt,
          category: item.category,
          type: 'news' as const,
          created_at: item.created_at,
          updated_at: item.updated_at
        }));
      items.push(...newsDrafts);
    }

    // 添加公告草稿
    if (announcementsData?.items && (contentType === 'all' || contentType === 'announcements')) {
      const announcementDrafts = announcementsData.items
        .filter(item => !item.is_published)
        .map(item => ({
          id: item.id,
          title: item.title,
          excerpt: item.excerpt,
          category: item.category,
          type: 'announcements' as const,
          created_at: item.created_at,
          updated_at: item.updated_at
        }));
      items.push(...announcementDrafts);
    }

    // 按更新时间排序
    return items.sort((a, b) => {
      const dateA = new Date(a.updated_at || a.created_at);
      const dateB = new Date(b.updated_at || b.created_at);
      return dateB.getTime() - dateA.getTime();
    });
  };

  const draftItems = getDraftItems();

  // 获取类型标签
  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'news': return '新闻';
      case 'announcements': return '公告';
      default: return type;
    }
  };

  // 获取类型颜色
  const getTypeColor = (type: string) => {
    switch (type) {
      case 'news': return 'bg-blue-100 text-blue-800';
      case 'announcements': return 'bg-orange-100 text-orange-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  // 获取编辑链接
  const getEditLink = (item: DraftItem) => {
    switch (item.type) {
      case 'news': return `/admin/news?edit=${item.id}`;
      case 'announcements': return `/admin/announcements?edit=${item.id}`;
      default: return '#';
    }
  };

  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* 页面头部 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-800">草稿箱</h1>
            <p className="text-gray-600">
              管理所有未发布的内容草稿
              <span className="ml-4 text-sm">
                <span className="text-orange-600">总草稿: {draftItems.length}</span>
              </span>
            </p>
          </div>
          <div className="flex space-x-3">
            <Link
              to="/admin/news"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
            >
              <i className="fa-solid fa-newspaper text-sm"></i>
              <span>新建新闻</span>
            </Link>
            <Link
              to="/admin/announcements"
              className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors flex items-center space-x-2"
            >
              <i className="fa-solid fa-bullhorn text-sm"></i>
              <span>新建公告</span>
            </Link>
          </div>
        </div>

        {/* 搜索和筛选 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0 md:space-x-4">
            <div className="flex-1">
              <input
                type="text"
                placeholder="搜索草稿标题..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div className="flex space-x-4">
              <select
                value={contentType}
                onChange={(e) => setContentType(e.target.value as ContentType)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="all">全部类型</option>
                <option value="news">新闻草稿</option>
                <option value="announcements">公告草稿</option>
              </select>
              <button
                type="button"
                onClick={() => {
                  setSearchTerm('');
                  setContentType('all');
                }}
                className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                重置
              </button>
            </div>
          </div>
        </div>

        {/* 草稿列表 */}
        <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
          {draftItems.length === 0 ? (
            <div className="text-center py-12">
              <i className="fa-solid fa-file-lines text-4xl text-gray-300 mb-4"></i>
              <p className="text-gray-500 text-lg mb-2">暂无草稿</p>
              <p className="text-gray-400 text-sm">创建新内容时选择"保存草稿"即可在此查看</p>
            </div>
          ) : (
            <div className="divide-y divide-gray-200">
              {draftItems.map((item) => (
                <div key={`${item.type}-${item.id}`} className="p-6 hover:bg-gray-50 transition-colors">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center space-x-3 mb-2">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getTypeColor(item.type)}`}>
                          {getTypeLabel(item.type)}
                        </span>
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                          {item.category}
                        </span>
                      </div>
                      
                      <h3 className="text-lg font-semibold text-gray-900 mb-2">
                        {item.title}
                      </h3>
                      
                      {item.excerpt && (
                        <p className="text-gray-600 text-sm mb-3 line-clamp-2">
                          {item.excerpt}
                        </p>
                      )}
                      
                      <div className="flex items-center text-sm text-gray-500">
                        <i className="fa-solid fa-calendar mr-1"></i>
                        <span>创建于 {new Date(item.created_at).toLocaleDateString('zh-CN')}</span>
                        {item.updated_at && item.updated_at !== item.created_at && (
                          <>
                            <span className="mx-2">•</span>
                            <i className="fa-solid fa-edit mr-1"></i>
                            <span>更新于 {new Date(item.updated_at).toLocaleDateString('zh-CN')}</span>
                          </>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex items-center space-x-3 ml-6">
                      <Link
                        to={getEditLink(item)}
                        className="inline-flex items-center px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors"
                      >
                        <i className="fa-solid fa-edit mr-2"></i>
                        编辑
                      </Link>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 统计信息 */}
        {draftItems.length > 0 && (
          <div className="bg-white p-4 rounded-lg shadow-sm border">
            <div className="text-sm text-gray-600">
              共找到 <span className="font-medium text-gray-900">{draftItems.length}</span> 个草稿
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
